const Resume = require('../models/Resume');
const fs = require('fs');
const path = require('path');
const { Op } = require('sequelize');
const { sendInterviewNotification } = require('../services/notification.service');

// 获取简历列表（企业筛选）
exports.getResumes = async (req, res) => {
  try {
    const { jobId, experience, education, keyword, page = 1, limit = 10 } = req.query;
    const offset = (page - 1) * limit;
    const whereClause = {};

// 下载简历模板
exports.downloadResumeTemplate = async (req, res) => {
  try {
    const templatePath = path.join(__dirname, '../templates/resume_template.docx');
    
    // 检查模板文件是否存在
    if (!fs.existsSync(templatePath)) {
      return res.status(404).json({
        success: false,
        message: '简历模板不存在，请联系管理员上传模板'
      });
    }
    
    // 设置响应头并下载文件
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    res.setHeader('Content-Disposition', 'attachment; filename="resume_template.docx"');
    res.download(templatePath);
  } catch (error) {
    console.error('下载简历模板失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，下载简历模板失败',
      error: error.message
    });
  }
};

    // 构建筛选条件
    if (jobId) whereClause.jobId = jobId;
    if (experience) whereClause.experience = { [Op.like]: `%${experience}%` };
    if (education) whereClause.highestEducation = { [Op.like]: `%${education}%` };
    if (keyword) {
      whereClause[Op.or] = [
        { fullName: { [Op.like]: `%${keyword}%` } },
        { skills: { [Op.like]: `%${keyword}%` } },
        { major: { [Op.like]: `%${keyword}%` } }
      ];
    }

    const { count, rows: resumes } = await Resume.findAndCountAll({
      where: whereClause,
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['updatedAt', 'DESC']],
      include: ['user']
    });

    res.status(200).json({
      success: true,
      data: {
        resumes,
        pagination: {
          total: count,
          page: parseInt(page),
          limit: parseInt(limit),
          pages: Math.ceil(count / limit)
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取简历列表失败',
      error: error.message
    });
  }
};

// 获取单个简历详情
exports.getResumeById = async (req, res) => {
  try {
    const { id } = req.params;
    const resume = await Resume.findByPk(id, {
      include: ['user']
    });

    if (!resume) {
      return res.status(404).json({
        success: false,
        message: '简历不存在'
      });
    }

    res.status(200).json({
      success: true,
      data: resume
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取简历详情失败',
      error: error.message
    });
  }
};

// 更新简历状态（筛选/标记）
exports.updateResumeStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status, remark } = req.body;

    const resume = await Resume.findByPk(id);
    if (!resume) {
      return res.status(404).json({
        success: false,
        message: '简历不存在'
      });
    }

    await resume.update({
      status,
      remark
    });

    res.status(200).json({
      success: true,
      message: '简历状态更新成功',
      data: resume
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新简历状态失败',
      error: error.message
    });
  }
};

// 发送面试通知
exports.sendInterview = async (req, res) => {
  try {
    const { resumeId, jobId, interviewTime, location, notes } = req.body;

    // 获取简历信息
    const resume = await Resume.findByPk(resumeId, {
      include: ['user']
    });

    if (!resume) {
      return res.status(404).json({
        success: false,
        message: '简历不存在'
      });
    }

    // 发送通知
    await sendInterviewNotification({
      userId: resume.userId,
      jobId,
      interviewTime,
      location,
      notes
    });

    // 更新简历状态为"已邀请面试"
    await resume.update({
      status: 'interview_invited',
      remark: `面试时间: ${interviewTime}, 地点: ${location}`
    });

    res.status(200).json({
      success: true,
      message: '面试通知发送成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '发送面试通知失败',
      error: error.message
    });
  }
};

// 求职者创建/更新简历
exports.upsertResume = async (req, res) => {
  try {
    const userId = req.user.id;
    const resumeData = req.body;

    // 查找用户是否已有简历
    let resume = await Resume.findOne({ where: { userId } });

    if (resume) {
      // 更新现有简历
      await resume.update(resumeData);
      res.status(200).json({
        success: true,
        message: '简历更新成功',
        data: resume
      });
    } else {
      // 创建新简历
      resume = await Resume.create({
        ...resumeData,
        userId
      });
      res.status(201).json({
        success: true,
        message: '简历创建成功',
        data: resume
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '创建/更新简历失败',
      error: error.message
    });
  }
};

// 求职者删除简历
exports.deleteResume = async (req, res) => {
  try {
    const userId = req.user.id;
    const { id } = req.params;

    const resume = await Resume.findOne({ where: { id, userId } });
    if (!resume) {
      return res.status(404).json({
        success: false,
        message: '简历不存在或无权删除'
      });
    }

    await resume.destroy();
    res.status(200).json({
      success: true,
      message: '简历删除成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '删除简历失败',
      error: error.message
    });
  }
};

// 获取当前求职者的简历
exports.getMyResume = async (req, res) => {
  try {
    const userId = req.user.id;
    const resume = await Resume.findOne({ where: { userId } });

    res.status(200).json({
      success: true,
      data: resume || null
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取个人简历失败',
      error: error.message
    });
  }
};